package com.abc.service.consumer.controller;

import com.abc.service.consumer.service.EchoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class HelloController {

    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    // Feign封装的远程调用接口
    @Autowired
    private EchoService echoService;

    @Value("${spring.application.name}")
    private String appName;

    // 使用最原始的方式调用服务提供者的api
    @GetMapping("/echo/app-name")
    public String echoAppName(){
        //Access through the combination of LoadBalanceClient and RestTemplate
        // 获取服务实例的引用
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-service-provider");
        // 通过服务实例的具体ip和端口拼接url
        String path = String.format("http://%s:%s/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
        System.out.println("request path:" +path);
        // 通过RestTemplate调用服务实例的接口
        return restTemplate.getForObject(path,String.class);
    }


    @GetMapping(value = "/feign/echo/app-name")
    public String echo() {
        return echoService.echo(appName);
    }


}
